package br.com.almanach.seguranca;

import br.com.almanach.jsf.JSFUtil;
import br.com.almanach.negocio.seguranca.UsuarioNegocio;
import br.com.almanach.web.Sessao;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@ManagedBean(name="login")
@RequestScoped
public class Login implements Serializable {

    private String nome;
    private String senha;

    @EJB
    private UsuarioNegocio usuarioNegocio;

    @ManagedProperty(value="#{sessao}")
    private Sessao sessao;

    public String logon()  throws IOException, ServletException {
        this.sessao.setUsuario(usuarioNegocio.buscar(this.nome, this.senha));
        if(this.sessao.getUsuario()==null){
            JSFUtil.mensagemErro(JSFUtil.getTextoMensagem("msg_falha_logon"));
        }else{
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check");
            dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
            FacesContext.getCurrentInstance().responseComplete();
        }
        return null;        
    }

    public String logout() throws IOException, ServletException {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_logout");
        dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
        FacesContext.getCurrentInstance().responseComplete();
        return "logout";
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public void setSessao(Sessao sessao) {
        this.sessao = sessao;
    }

}
